<?php

namespace App\Http\Queries;

use App\Http\Business\PowerBusiness;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Spatie\QueryBuilder\QueryBuilder;

class BaseQuery extends QueryBuilder
{
    // 字符搜索
    protected $strSearch = [];
    // 等值搜索
    protected $eqSearch = [];
    // 时间搜索
    protected $timeSearch = [];
    //时间搜索属性
    protected $timeAttribute = '';


    /**
     * BaseQuery constructor.
     *
     * @param \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation $builder
     * @param null|\Illuminate\Http\Request $request
     */
    public function __construct($builder, ?Request $request = null)
    {
        parent::__construct($builder, $request);

        foreach ($this->strSearch as $key){
            $this->request->has($key) && $this->where($key, 'like', '%' . $this->request->input($key) . '%');
        }
        foreach ($this->eqSearch as $key){
            $map = [];
            $this->request->has($key) && $map[$key] = $this->request->input($key);
            count($map) > 0 && $this->where($map);
        }

        if ($this->timeAttribute && count($this->timeSearch) > 0){
            $this->request->has($this->timeSearch[0]) && $this->where($this->timeAttribute, '>', $this->request->input($this->timeSearch[0]));;
            $this->request->has($this->timeSearch[1]) && $this->where($this->timeAttribute, '<', $this->request->input($this->timeSearch[1]));;
        }

    }

    public function getPageSize($key = 'pageSize')
    {
        $allowPageSize = [15, 20, 40, 60, 100];
        $pageSize = $this->request->input($key, 15);
        if (!in_array($pageSize, $allowPageSize)){
            $pageSize = $allowPageSize[0];
        }

        return $pageSize;
    }

    public function toOrderBy($key = 'orderBy', $by = 'type')
    {
        $attribute = $this->request->input($key, 'created_at');
        $type = $this->request->input($by, 'desc');

        $this->orderBy($attribute, $type);

        return true;

    }

    /**
     * 判断用户是否需要过滤不是自己的数据：返回用户ID则需要，返回false则不需要
     * @param string $guard
     * @return bool
     */
    public function getOwnPower($guard='admin')
    {
        $user = Auth::guard($guard)->user();
        if (PowerBusiness::isSuperAdmin($user->phone)){
            return false;
        }

        $res = $user->user_id;
        foreach ($user->roles as $role){
            if ($role->pivot->own_power == 0){
                $res = false;
            }
        }

        return $res;
    }
}
